package com.ctsi.framework.mybatis.dialect;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * Oracle数据库的分页SQL
 * 
 * @author zhangjw
 */
public class OraDialect extends AbstractMiDialect {
	private static final Logger logger = LoggerFactory.getLogger(OraDialect.class);

	@Override
	public void setLimitParamters(PreparedStatement ps, int parameterSize, int offset, int limit) throws SQLException {
		if (offset >= 0) {
			ps.setInt(parameterSize + 1, offset + limit);
			ps.setInt(parameterSize + 2, offset);
		} else {
			ps.setInt(parameterSize + 1, limit);
		}
	}

	@Override
	public String getLimitString(String sql, int offset) {
		sql = sql.trim();
		logger.debug("Origianl SQL is ：{}", sql);
		boolean isForUpdate = false;
		if (sql.toLowerCase().endsWith(" for update")) {
			sql = sql.substring(0, sql.length() - 11);
			isForUpdate = true;
		}
		StringBuilder pagingSelect = new StringBuilder(sql.length() + 100);
		if (offset >= 0) {
			pagingSelect.append("select * from ( select row_.*, rownum rownum_ from ( ");
		} else {
			pagingSelect.append("select * from ( ");
		}
		pagingSelect.append(sql);
		if (offset >= 0) {
			pagingSelect.append(" ) row_ ) where rownum_ <= ?").append(" and rownum_ > ?");
		} else {
			pagingSelect.append(" ) where rowEnd_ <= ?");
		}

		if (isForUpdate) {
			pagingSelect.append(" for update");
		}
		logger.debug("Generation SQL is : {}", pagingSelect);
		return pagingSelect.toString();
	}

	@Override
	public boolean supportsLimitOffset() {

		return true;
	}
}
